<template>
  <!-- CreateMemberCoupon 创建福利券 -->
  <PageContainer>
    <view class="container">
      <Header title="创建" :is-box-shadow="false" />
      <view class="form-container">
        <BasicsForm
          :disabled="isEdit"
          @register="basicsFormRegister"
          :btn-group-options="
            !isEdit
              ? {
                  submit: {
                    text: '提交',
                  },
                }
              : {}
          "
          @submit="formSubmit"
        >
          <template #dynamicSlot="{ model, field }">
            <view class="permission" @click="toSeclect(model[field])">
              <view class="permission-top">
                <text>{{ getPermissionText(model[field]) }}</text>
                <text class="ali-icon">&#xe6c7;</text>
              </view>
              <view v-if="positionList.length" class="permission-bot">
                <template v-for="v in positionList" :key="v.id">
                  <text>{{ v.name }}({{ v.count }})，</text>
                </template>
              </view>
            </view>
          </template>
        </BasicsForm>
      </view>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  CreateMemberCoupon  创建福利券 */

  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import { navigateTo, onLoad, redirectTo } from '@/router';
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { type FormSchema, useForm } from '@/components/Form';
  import {
    MemberCouponDitchTypeEnum,
    MemberCouponPermissionsEnum,
    MemberCouponTypeEnum,
  } from '@/enums/memberCouponEnum';
  import dictionary from '@/utils/dictionary';
  import { ref } from 'vue';
  import { memberCouponAdd, myCouponHistoryDetails } from '@/api/memberCoupon';
  import {
    type MemberCouponAddData,
    type MyCouponHistoryDetailsResult,
  } from '@/api/memberCoupon/types';
  import { UniEmitNameEnum } from '@/enums/uniEmitEnum';
  import { type GetDownStatisticsListResult } from '@/api/indexTypes';
  import { getDownStatisticsList } from '@/api';
  import { type CreateMemberCoupon } from '@/router/types/modules';

  const schemas: FormSchema[] = [
    {
      field: 'name',
      label: '券名称',
      component: 'Input',
      required: true,
    },
    {
      field: 'type',
      label: '券类型',
      component: 'RadioGroup',
      required: true,
      defaultValue: MemberCouponTypeEnum.WELFARE,
      componentProps: {
        localdata: [
          {
            text: '福利券',
            value: MemberCouponTypeEnum.WELFARE,
          },
        ],
      },
    },
    {
      field: 'ditchType',
      label: '上架渠道',
      component: 'RadioGroup',
      required: true,
      defaultValue: MemberCouponDitchTypeEnum.PERSONAL_CARD,
      componentProps: {
        localdata: [
          {
            text: '个人名片',
            value: MemberCouponDitchTypeEnum.PERSONAL_CARD,
          },
        ],
      },
    },
    {
      field: 'couponCover',
      label: '封面图',
      component: 'UploadImg',
      defaultValue:
        'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/obs/20221124/21854d536b74428980eb01d9d9355753.png',
      required: true,
      componentProps: {
        isCrop: true,
        cropOptions: {
          width: 690,
          height: 552,
        },
      },
    },
    {
      field: 'couponNumber',
      label: '发放数量',
      component: 'NumberBox',
      required: true,
    },
    {
      field: 'validityStartTime',
      label: '有效期开始',
      component: 'DatePicker',
      required: true,
    },
    {
      field: 'validityEndTime',
      label: '有效期结束',
      component: 'DatePicker',
      required: true,
    },
    {
      field: 'couponRole',
      label: '谁可以看',
      component: 'Input',
      slot: 'couponRole',
      defaultValue: MemberCouponPermissionsEnum.PUBLIC,
      required: true,
    },
    {
      field: 'introduction',
      label: '简介',
      component: 'InputTextArea',
      required: true,
    },
    {
      field: 'explainUrl',
      label: '使用说明',
      component: 'UploadImg',
      componentProps: {
        limit: 1
      }
    },
  ];
  const [formRegister, { setFieldsValue }] = useForm({
    labelPosition: 'left',
    labelAlign: 'left',
    labelWidth: 100,
    validateTrigger: 'submit',
    schemas: schemas,
  });

  function basicsFormRegister(event: any) {
    formRegister(event);
    setVals();
  }

  /** 去选择权限 */
  const positionList = ref<GetDownStatisticsListResult[]>([]);
  function toSeclect(type: MemberCouponPermissionsEnum) {
    if (isEdit.value) return;
    navigateTo({
      name: 'couponSelectPermissions',
      options: {
        role: Number(type),
        positionList: positionList.value,
        success: (data) => {
          positionList.value = data.positionList;
          setFieldsValue({
            couponRole: data.role,
          });
        },
      },
    });
  }

  const getPermissionText = (type: MemberCouponPermissionsEnum) => {
    const dists = dictionary.getLocal('ticketPermissions');
    return dists.find((v) => v.dictValue == type)?.dictLabel;
  };

  function formSubmit(data: MemberCouponAddData) {
    let memberLeveIdList: number[] = [];
    if (positionList.value) memberLeveIdList = positionList.value.map((v) => v.id);
    memberCouponAdd({ ...data, memberLeveIdList }).then((r) => {
      success.value?.();
      historyItem.value && uni.$emit(UniEmitNameEnum.REFRESHPREVIOUSPAGE);
      redirectTo({ name: 'createCouponResult', options: r });
    });
  }

  function getDetails() {
    id.value &&
      myCouponHistoryDetails(id.value).then(async (r) => {
        let postList: GetDownStatisticsListResult[] = [];
        if (r.couponRole === MemberCouponPermissionsEnum.SICHTTEIL && r.memberLeveIdList.length) {
          const levelList = await getDownStatisticsList();
          levelList.forEach((v) => r.memberLeveIdList.includes(v.id) && postList.push(v));
        }
        historyItem.value = r;
        positionList.value = postList;
        setVals();
      });
  }

  function setVals() {
    if (historyItem.value) {
      const obj: Recordable = {};
      schemas.forEach((v) => {
        const k = v.field as keyof MyCouponHistoryDetailsResult;
        if (historyItem.value && historyItem.value.hasOwnProperty(k)) obj[k] = historyItem.value[k];
      });
      setFieldsValue(obj);
    }
  }

  const success = ref<CreateMemberCoupon['success']>();
  const historyItem = ref<CreateMemberCoupon['historyItem']>();
  const id = ref<number>();
  const isEdit = ref<boolean>();
  onLoad<'CreateMemberCoupon'>((op) => {
    success.value = op.success;
    isEdit.value = op.isEdit;
    if (op.id) {
      id.value = op.id;
      getDetails();
    }
  });
</script>

<style lang="scss" scoped>
  .form-container {
    border-top: 30rpx solid #fff;
  }
  .permission {
    color: #333;
    font-size: 28rpx;
    width: 100%;
    height: 36px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: center;
    &-top {
      display: flex;
      align-items: center;
    }
    &-bot {
      font-size: 24rpx;
      color: #aaabab;
    }
    .ali-icon {
      font-size: 48rpx;
    }
  }
</style>
